using MyTimer;
using Services;
using System.Collections;
using UnityEngine;

public class Interlude : MonoBehaviour
{
    private Vector2 offset;

    private UniformLinearMotion motion;
    [SerializeField]
    private RectTransform rectTransform_leftCurtain;
    private Vector2 leftPosition;
    [SerializeField]
    private RectTransform rectTranform_rightCurtain;
    private Vector2 rightPosition;

    private void Awake()
    {
        DontDestroyOnLoad(gameObject);
        ServiceLocator.Get<SceneController>().AsyncLoadScene += OnLoadScene;
        leftPosition = rectTransform_leftCurtain.anchoredPosition;
        rightPosition = rectTranform_rightCurtain.anchoredPosition;
        offset = new Vector3(450f, 0f);
        motion = new UniformLinearMotion();
        motion.Initialize(offset, Vector2.zero, 0.5f, false);
        motion.Tick += OnUpdate;
        motion.Complete += OnComplete;
    }

    private void OnLoadScene(AsyncOperation operation)
    {
        if (SceneControllerUtility.SceneIndex >= SceneController.MenuIndex)
        {
            rectTransform_leftCurtain.anchoredPosition = leftPosition + offset;
            rectTranform_rightCurtain.anchoredPosition = rightPosition - offset;
            StartCoroutine(WaitForLoadScene(operation));
        }
    }

    private void OnUpdate(Vector3 current)
    {
        rectTransform_leftCurtain.anchoredPosition = leftPosition + current.RemoveZ();
        rectTranform_rightCurtain.anchoredPosition = rightPosition - current.RemoveZ();
    }

    private void OnComplete(Vector3 current)
    {
        rectTransform_leftCurtain.transform.position = leftPosition + current.RemoveZ();
        rectTranform_rightCurtain.transform.position = rightPosition - current.RemoveZ();
        motion.Paused = true;
    }

    private IEnumerator WaitForLoadScene(AsyncOperation operation)
    {
        for (; !operation.isDone;)
        {
            yield return null;
        }
        motion.Restart();
    }
}
